var mapaController = {

    expandMapComponent: {
        defs: {
            load: false,
            mapContainer: $('#cooperativas-container'),
            markerDetailsContainer: $('#marker-details-container'),
            elementsNoExpand:$('#marker-details-container, #informacion-container, #footer, #botonera'),
            elementsExpand:$('#cooperativas-box, #markers-list, #scrollbar, #category-list-container, .viewport')
        },
        bind: function(){
            var self = this;
            var alto = $(window).height() - 142;
            $('#btn-expand-cooperativas').toggle(
                function () {
                    self.defs.elementsExpand.css({
                        height:alto-4
                    });
                    self.defs.elementsNoExpand.hide();
                    self.defs.mapContainer.addClass('expanded-map');
                    google.maps.event.trigger(mapaController.map.defs.map, "resize");
                },
                function () {
                    self.defs.elementsExpand.attr('style', '');
                    self.defs.elementsNoExpand.show();
                    self.defs.mapContainer.removeClass('expanded-map');
                    google.maps.event.trigger(mapaController.map.defs.map, "resize");
                }
                )
            $(window).resize(function () {
                alto = $(window).height() - 142;
                if (self.defs.mapContainer.hasClass('expanded-map')) {
                    self.defs.elementsExpand.css({
                        height:alto-4
                    });
                }
            })
        },
        init: function(){
            if ($(window).width() > 767) this.bind();
        }
    },

    scrollToComponent: {
        defs: {
            load: false
        },
        load: function(){
            var componentsPath = scriptsController.defs.baseUrl + scriptsController.defs.componentsPath + 'scrollto/',
            self = this;
            $.getScript(componentsPath + 'jquery.scrollTo-1.4.2-min.js', function(){
                self.defs.load = true;
                self.bind();
            });
        },
        
        bind: function(){
            var top;
            $('.scroll-to').click(function(e){
                e.preventDefault();
                top = (($($(this).attr('href')).position()).top)-100;
                $.scrollTo(top, 800);
            });
            if ($(window).width() < 768) {
                $('.category-list .link').click(function(e){
                    e.preventDefault();
                    top = (($('#cooperativas-content').position()).top)-40;
                    $.scrollTo(top, 800);
                });

                $('.back-to-map').click(function(e){
                    e.preventDefault();
                    top = (($('#cooperativas-content').position()).top)-40;
                    $.scrollTo(top, 800);
                });
            }
        },
        init: function(){
            if (!!!this.defs.load) this.load();
        }
    },

    getContent: {
        get: function(){
	    self = this;
	    $.ajax({
		url:scriptsController.defs.baseUrl+'controllers/categoriaController/findAll',
		success: function (data) {
		    if (data){
			mapaController.polygons.init(data['categorias']);
		    }
		}
	    })
	},
        init:function () {
            this.get();
        }
    },
    
    polygons: {
        defs: {
            baseUrl:scriptsController.defs.baseUrl,
            categorias: [],
	    idsCategorias: []
        },
        options:{
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillOpacity: 0.35
        },
        zonas: [], //informacion dinamica que viene de base
        bind: function (polygon) {
            self = this;
            google.maps.event.addListener(polygon, 'click', function(e) {
                self.changeUrlByPolygon(polygon)
                self.mostrarDetallesCooperativa(polygon.id)
                $.scrollTo('#marker-details-container',800,{offset:-45})
            });
            mapaController.infobox.bind(mapaController.map.defs.map, polygon);
        },
        mostrarDetallesCooperativa: function (id) {
            $('#marker-details-container header').show();
            scriptsController.loader.append($('#marker-details-container header .wait'), 'tiny');
            var self = this;
            var detallesMarkerTpl = document.getElementById('detallesMarkerTpl').innerHTML;
            $.ajax({
                url:self.defs.baseUrl+'controllers/cooperativaController/detalles/'+id,
                success:function (data) {
                    var tips = data.marker.tip || document.getElementById('noTipsTpl').innerHTML;
                    detallesMarkerTpl = detallesMarkerTpl.replace(/\$\{markerNombre\}/g, data.marker.nombre)
                    .replace(/\$\{markerTipo\}/g, data.marker.tipo)
                    .replace(/\$\{markerDireccion\}/g, data.marker.direccion)
                    .replace(/\$\{markerHorario\}/g, data.marker.horario)
                    .replace(/\$\{markerEmail\}/g, data.marker.email)
                    .replace(/\$\{markerWeb\}/g, data.marker.web)
                    .replace(/\$\{markerFrase\}/g, data.marker.frase)
                    .replace(/\$\{markerTelefono\}/g, data.marker.telefono)
                    .replace(/\$\{markerDescripcion\}/g, data.marker.descripcion)
                    .replace(/\$\{markerFavoritos\}/g, data.marker.favoritos)
                    .replace(/\$\{markerTips\}/g, data.marker.tips)
                    .replace(/\$\{images}/g, data.images)
                    .replace(/\$\{tips\}/g, tips)
                    .replace(/\$\{reciben\}/g, mapaController.classyCategories.create(data.marker.categoriasToIds, self.defs.categorias))
                    .replace(/\$\{[a-zA-Z]+\}/g, '');
                    scriptsController.loader.remove($('#marker-details-container header .wait'));
                    $('#marker-details-container article').html(detallesMarkerTpl).slideDown(600, function(){
                        $('#marker-menu-container').height($(this).outerHeight()-5);
		    });
                    mapaController.comentManager.init();
                    
                    FB.XFBML.parse();
		    $('#twbtn iframe, #twbtn .twitter-share-button').remove();
		    $('#twbtn').append('<a href="https://twitter.com/share" class="twitter-share-button" data-text="Donde Reciclo - '+data.marker.nombre+'" data-url="'+scriptsController.defs.baseUrl+'cooperativas/'+data.marker.nombreUrl+'/'+id+'" data-lang="es">Twittear</a>')
		    twttr.widgets.load();
                    
                    //oculta lo que no tiene info
                    if (!data.marker.descripcion)$('#description-item').remove();
                    if (!data.marker.telefono)$('#phone-item').remove();
                    if (!data.marker.horario)$('#hour-item').remove();
                    if (!data.marker.email)$('#email-item').remove();
                    if (!data.marker.web)$('#web-item').remove();
                    if (!data.images)$('#fotos-row').remove();
                    
                    mapaController.fancybox.init();
                }
            })
        },
        changeUrlByPolygon:function (marker) {
            var self = this;
            var hash = marker.nombreUrl+'/'+marker.id;
            document.getElementById('markerId').value = marker.id
            if (navigator.appName == "Microsoft Internet Explorer") {//si es explorer
                if (window.location.href.indexOf('#') == -1) {
                    document.location = self.defs.baseUrl+'cooperativas/#!/'+hash;
                } else {
                    document.location.hash = '#!/'+hash;
                }
            } else {//si es otro navegador
                window.history.replaceState('', marker.nombre, self.defs.baseUrl+'cooperativas/'+hash);
            }
        },
        setCategorias: function (categorias) {
	    for (var i in categorias) {
		var cat = new Categoria ();
		cat.nombre = categorias[i]['nombre']
		cat.identificador = categorias[i]['identificador']
		this.defs.categorias[i] = cat;
		this.defs.idsCategorias[categorias[i]['identificador']] = i;
	    }
	},
        create: function () {
            var zona = null;
            var self = this, color;
            $.getJSON(self.defs.baseUrl+'controllers/cooperativaController/findAll', function(zonas) {
                for (var i in zonas) {
                    color = '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6)
                    zona = new google.maps.Polygon({
                        paths: eval(zonas[i].polygon),
                        strokeColor: color,
                        strokeOpacity: self.options.strokeOpacity,
                        strokeWeight: self.options.strokeWeight,
                        fillColor: color,
                        fillOpacity: self.options.fillOpacity,
                        id: zonas[i].id,
                        info: zonas[i].info,
                        nombre: zonas[i].nombre,
                        nombreUrl: zonas[i].nombreUrl,
                        centro: eval(zonas[i].centro)
                    });
                    zona.setMap(mapaController.map.defs.map);
                    self.bind(zona);
                }
            });
        },
        init: function (categorias) {
            this.setCategorias(categorias);
            this.create();
        }
    },

    map: {
        defs:{
            center: new google.maps.LatLng(-34.603526, -58.381586), //buenos aires
            map:null,
            mapContainer: document.getElementById("cooperativas-box"),
            options: {
                zoom: 11,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            },
            baseUrl:scriptsController.defs.baseUrl,
            markerDetailsContainer:document.getElementById('marker-details-container')
        },
        dynamicUrlParser: function () {
            var url = document.location + '';
            url = url.replace(this.defs.baseUrl+'cooperativas/', '')
            .replace('#!/', '')
            .replace(/\/$/, '');
            if (url) {
		var self = this, params = '';
		this.defs.urlMarker = true;
                params = url.split('/')
		var id = params[1].replace(/[^0-9]/ig, '');
                $.ajax({
                    url:this.defs.baseUrl+'controllers/cooperativaController/find/'+id,
                    success:function (data) {
                        //self.defs.map.panTo(eval(data.centro));
                        mapaController.polygons.mostrarDetallesCooperativa(id)
                    }
                })
	    }
        },
        init: function () {
            this.defs.map = new google.maps.Map(this.defs.mapContainer, this.defs.options);
            this.defs.map.setCenter(this.defs.center);
            this.dynamicUrlParser();
        }
    },

    infobox:{
        defs:{
            tpl:document.getElementById('infoboxContent')
        },
        options: {
            content: '',
            disableAutoPan: false,
            maxWidth: 0,
            pixelOffset: new google.maps.Size(0, -30),
            zIndex: null,
            closeBoxURL: '',
            infoBoxClearance: new google.maps.Size(1, 1),
            isHidden: false,
            pane: 'floatPane',
            enableEventPropagation: false
        },
        createInfoboxHtml: function (polygon) {
            var content = this.defs.tpl.value.replace(/\$\{polygonNombre\}/g, polygon.nombre)
            .replace(/\$\{polygonInfo\}/g, polygon.info)
            .replace(/\$\{[a-zA-Z]+\}/g, '')
            ;
            var container = document.createElement('div');
            container.className = 'infobox';
            var target = document.createElement('div');
            target.className = 'target';
            container.innerHTML = content;
            container.appendChild(target);
            return {
                container:container, 
                target:target
            }
        },
        bind: function (mapa, polygon) {
            /*var self = this;
            var infobox = new InfoBox(self.options);
            var infoboxHtml = self.createInfoboxHtml(polygon);
            infobox.setContent(infoboxHtml.container);
            polygon.infobox = infobox;
            google.maps.event.addListener(polygon, "mouseover", function () {
                if (self.currentInfobox != undefined) self.currentInfobox.close();
                var marker = new google.maps.Marker({position: this.centro});
                polygon.infobox.open(mapa, marker);
                self.currentInfobox = polygon.infobox;
            })
            google.maps.event.addListener(polygon, "mouseout", function (e) {
                polygon.infobox.close()
            });*/
        }
    },
    
    comentManager : {
        init: function () {
            this.bind();
        },
        bind: function () {
            var enviador = document.getElementById('btn-send-comment');
            if (enviador) {
                enviador.onclick = function () {
                    var self = this;
                    self.className += ' disabled'
                    self.innerHTML = 'Espere...';
                    var comentario = document.getElementById('comment-field').value;
                    var cooperativaId = document.getElementById('cooperativaId').value;
                    var tipTpl = document.getElementById('tipTpl').innerHTML;
                    $.ajax({
                        url:scriptsController.defs.baseUrl+'controllers/comentarioController/cooperativa/',
                        data: 'comentario='+comentario+'&cooperativaId='+cooperativaId,
                        type:'post',
                        success:function (data) {
                            self.innerHTML = 'Enviar';
                            self.className = self.className.replace(' disabled', '');
                            tipTpl = tipTpl.replace(/\$\{owner}/g, data)
                            .replace(/\$\{comentario\}/g, comentario)
                            document.getElementById('tips-list').innerHTML = tipTpl + document.getElementById('tips-list').innerHTML;
                        }
                    })
                    return false;
                }
            }
        }
    },
    
    classyCategories: {
	create: function (c, ctgs) {
	    c = c.split(',');
	    var html = '';
	    for (var i=0, l=c.length; i<l; i++) {
                if (ctgs[c[i]] == undefined)continue;
		html += '<em class="recive-item '+ctgs[c[i]].identificador+'-item label"><span class="bg-color"></span><span class="val">'+ctgs[c[i]].nombre+'</span></em>';
	    }
	    return html;
	}
    },
    
    fancybox: {
        init: function () {
            $("a[rel=example_group]").fancybox({
                'transitionIn'		: 'none',
                'transitionOut'		: 'none'
            });
        }
    },

    init: function(){
        this.expandMapComponent.init();
        this.scrollToComponent.init();
        this.getContent.init();
        this.map.init();
    }
}

$(function(){
    FB.init({
        appId:'321221204603640',
        status:true, 
        cookie:true,
        FBxfbml:true,
        oauth:true
    });
    mapaController.init();
});

function Categoria () {
    this.markers = new Array ();
    this.identificador = new String ();
    this.nombre = new String ();
}